# -*- coding: utf-8 -*-
# This code written by ChanGOGOGO
"""
话单日结(线路商)
"""
from util import (
    query_es,
    ms2min,
    date_slice,
    write_excel,
    logging,
    time,
    excel_save_dir,
)


class ExportDailyBillsByLine:
    def __init__(self, ui_data):
        self.data_date = ui_data["data_date"]
        self.business = ui_data.get("business")
        self.data_type = ui_data.get("data_type")
        self.call_type = ui_data.get("call_type")
        self.start_time = ui_data.get("start_time")
        self.end_time = ui_data.get("end_time")
        company_id = ui_data.get("company_id")
        self.db_name = f"yicall_{company_id}"
        self.table_index = ui_data.get("business_id")
        if self.call_type == "呼出":
            self.es_index = f"{self.db_name}_{self.table_index}_callout_session_ach_{self.data_date}"
        else:
            self.es_index = f"{self.db_name}_{self.table_index}_callout_session_in_ach_{self.data_date}"

    def query_es_data(self, day_start_time, day_end_time):
        """按天查询es数据"""
        body = {
            "query": {
                "bool": {
                    "must": [
                        {"term": {"calloutConnectStatus": 100}},
                        {
                            "range": {
                                "calloutFinishTime": {
                                    "gte": day_start_time,
                                    "lte": day_end_time,
                                }
                            }
                        },
                    ]
                }
            }
        }
        fields = ["dialogDuration", "calloutDialNumber", "calloutDialTime"]
        day_es_data = query_es(self.es_index, body, fields)
        return day_es_data

    def export(self):
        # 以“天”为单位查询es数据，处理每天的数据，然后把每天的数据加入到汇总
        bill_info = {}  # 总账单
        date_slice_result = date_slice(self.start_time, self.end_time)
        for everyday in date_slice_result:
            day_start_time = everyday[0]
            day_end_time = everyday[1]
            es_data = self.query_es_data(day_start_time, day_end_time)
            for data in es_data:
                dialog_duration_ms = data.get("dialogDuration")  # 通话毫秒
                dialog_duration_min = ms2min(int(dialog_duration_ms))  # 计费分钟
                line_number = data.get("calloutDialNumber")  # 主叫号码
                callout_date = data.get("calloutDialTime")[:10]  # 拨打日期
                find_callout_date = bill_info.get(callout_date, -1)
                if find_callout_date == -1:  # 查找有没有callout_date这一天的统计数据
                    bill_info[callout_date] = {line_number: dialog_duration_min}
                else:
                    find_dial_number = bill_info.get(callout_date).get(line_number, -1)
                    if find_dial_number == -1:
                        bill_info[callout_date][line_number] = dialog_duration_min
                    else:
                        bill_info[callout_date][line_number] += dialog_duration_min
        excel_names = list()
        if bool(bill_info) is False:
            msg = (
                f"<font color=green>无法导出“{self.business}”的【{self.data_type}】，"
                f"原因：\n在{self.start_time}至{self.end_time}没有{self.call_type}数据！</font>"
            )
            logging.info(msg)
            return {"code": 1, "excel_names": [], "msg": msg}
        else:
            if self.call_type == "呼出":
                excel_title = ["日期", "主叫号码", "通话时长(分)"]
            else:
                excel_title = ["日期", "被叫号码", "通话时长(分)"]
            excel_data = list()
            callout_date_order = sorted(bill_info.keys())
            for callout_date in callout_date_order:
                callinfos = bill_info.get(callout_date)
                for dial_number, dialog_duration_min in callinfos.items():
                    excel_data.append([callout_date, dial_number, dialog_duration_min])
            file_name = (
                f"{self.business}_({self.call_type}){self.data_type}_{self.data_date}"
            )
            write_excel_start_time = time.time()
            excel_name = write_excel(
                [[self.data_type, excel_title, excel_data]], excel_save_dir, file_name
            )
            excel_names.append(excel_name)
            write_excel_end_time = time.time()
            write_excel_take_time = write_excel_end_time - write_excel_start_time
            logging.info(
                f"将{self.business}的{self.data_type}写入excel共计耗时{write_excel_take_time:.2f}秒。"
            )
            return {"code": 0, "excel_names": excel_names, "msg": None}


if __name__ == "__main__":
    ...
